package com.ff.javamonkey.ui;

import java.io.File;
import java.util.Properties;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.ff.javamonkey.R;
import com.ff.javamonkey.socket.MyProgressMonitor;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.SftpProgressMonitor;

public class ClientConnectActivity extends Activity {
	// Debugging
	private static final String TAG = "ClientConnectActivity";
	// Copy pasted from Zul.
	String username = "";
	String pass		= "";
	String host		= "";
	int port;
	private Context context;
	RelativeLayout formServer;
	EditText txtCommand;
	TextView txtResult;
	JSch jsch;
	Session session;
	
	String path;
	private static String help =
  	  "Available commands:\n"+
  	  "* means unimplemented command.\n\n"+
  	  "cd path                       							Change remote directory to 'path'\n"+
  	  "lcd path                      							Change local directory to 'path'\n"+
  	  "chgrp grp path                						Change group of file 'path' to 'grp'\n"+
  	  "chmod mode path               					Change permissions of file 'path' to 'mode'\n"+
  	  "chown own path                					Change owner of file 'path' to 'own'\n"+
  	  "help                          							Display this help text\n"+
  	  "get remote-path [local-path]  				Download file\n"+
  	  "get-resume remote-path [local-path]  	Resume to download file.\n"+
  	  "get-append remote-path [local-path]  		Append remote file to local file\n"+
  	  "*lls [ls-options [path]]      					Display local directory listing\n"+
  	  "ln oldpath newpath            					Symlink remote file\n"+
  	  "*lmkdir path                  						Create local directory\n"+
  	  "lpwd                          							Print local working directory\n"+
  	  "ls [path]                     							Display remote directory listing\n"+
  	  "*lumask umask                 					Set local umask to 'umask'\n"+
  	  "mkdir path                    						Create remote directory\n"+
  	  "put local-path [remote-path]  				Upload file\n"+
  	  "put-resume local-path [remote-path]  	Resume to upload file\n"+
  	  "put-append local-path [remote-path]  	Append local file to remote file.\n"+
  	  "pwd                           							Display remote working directory\n"+
  	  "stat path                     							Display info about path\n"+
  	  "exit                          							Quit sftp\n"+
  	  "quit                          							Quit sftp\n"+
  	  "rename oldpath newpath        				Rename remote file\n"+
  	  "rmdir path                    						Remove remote directory\n"+
  	  "rm path                       						Delete remote file\n"+
  	  "symlink oldpath newpath       				Symlink remote file\n"+
  	  "readlink path                 						Check the target of a symbolic link\n"+
  	  "realpath path                 						Canonicalize the path\n"+
  	  "rekey                         							Key re-exchanging\n"+
  	  "compression level             					Packet compression will be enabled\n"+
  	  "version                       							Show SFTP version\n"+
  	  "?                             							Synonym for help";
	File wallpaperDirectory;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);setContentView(R.layout.connect_form);
        context = this;

        wallpaperDirectory = new File("/sdcard/ff_file/");
	     // have the object build the directory structure, if needed.
	    if (!wallpaperDirectory.exists()) {
	        wallpaperDirectory.mkdirs();
	    }

     formServer = (RelativeLayout) findViewById(R.id.formServer);
        formServer.setVisibility(View.GONE);
        
        final TextView txtUsername	= (TextView) findViewById(R.id.txtUserName);
        txtUsername.setText("amds");
        final TextView txtPass		= (TextView) findViewById(R.id.txtPass);
        txtPass.setText("amds");
        final TextView txtHost		= (TextView) findViewById(R.id.txtHost);
        txtHost.setText("172.18.22.160");
        final TextView txtPort		= (TextView) findViewById(R.id.txtPort);
        txtPort.setText("5080");
        txtCommand = (EditText) findViewById(R.id.txtCommand);
        txtResult = (TextView) findViewById(R.id.txtResult);
        Button btnSave			= (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				username	= txtUsername.getText().toString();
				pass		= txtPass.getText().toString();
				host		= txtHost.getText().toString();
				port		= Integer.parseInt(txtPort.getText().toString());
				try {
					new AlertDialog.Builder(v.getContext())
						.setTitle("Output")
						.setMessage(getConnect(username, pass, host, port))
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			    	    	   public void onClick(DialogInterface dialog, int id) {
			    	    		   dialog.cancel();
			    	    		   formServer.setVisibility(View.VISIBLE);
			    	    	   }
		    	    	   })
						.show();
				} catch (Exception e) {
					e.printStackTrace();
					Log.e("CheckConnectActivity", e.getMessage());
					Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
				}	
			}
		});
        Button btnTcp = (Button) findViewById(R.id.btnCancel);
        btnTcp.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Intent intent = new Intent(context, CheckTCPConnectActivity.class);
				//startActivity(intent);
			}
		});
        
        txtCommand.setOnTouchListener(new OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				if (!txtCommand.getText().equals("")) {
					txtCommand.setText("");
				}
				return false;
			}
		});
        
        txtCommand.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				try {
					 getSftpResult(txtCommand.getText().toString());
					 txtCommand.setFocusable(true);
				} catch (Exception e) {
					e.printStackTrace();
					Log.e("CheckConnectActivity", e.getMessage());
					Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
				}
				return false;
			}
		});
	}
	
	private String getConnect(String username, String pass, String host, int port) throws Exception {
		String status = "";
		jsch = new JSch();
		session = jsch.getSession(username, host, port);
		session.setPassword(pass);
		
		Properties prop = new Properties();
		prop.put("StrictHostKeyChecking", "no");
		
		session.setConfig(prop);
		session.connect();
		if (session.isConnected()) {
			status = "Connect";
			return status; 
		}
		else {
			status = "unable to connect";
			return status;
		}
	}
	private void getSftpResult(String command) throws Exception {
		String cmd = command;
		
		jsch = new JSch();
		session = jsch.getSession(username, host, port);
		session.setPassword(pass);
		
		Properties prop = new Properties();
		prop.put("StrictHostKeyChecking", "no");
		
		session.setConfig(prop);
		session.connect();

		if (session.isConnected()) {
			Channel channel = session.openChannel("sftp");
			channel.connect();
			if (channel.isConnected()) {
				ChannelSftp cSftp = (ChannelSftp) channel;
				
				Vector<String> cmds = new Vector<String>();
				int level = 0;
				
					txtCommand.setText("");
					if (cmd != null && !cmd.equals("")) {
				  	  txtResult.setText("unimplemented command : "+cmd);
				  	  
				  	  String[] explode = cmd.split(" ");
						if (explode != null && explode.length > 1) {
							if (explode[0].equals("cd") || explode[0].equals("lcd")) {
								path = explode[1];
								try {
									if (explode[0].equals("cd")) cSftp.cd(path);
									else cSftp.lcd(path);
									txtResult.setText("");
								}
								catch (SftpException e) {
									Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
								}
							}
						}
						if (cmd.equals("quit")) {
							cSftp.quit();
						}
						if (cmd.equals("exit")) {
							cSftp.exit();
						}
						if (cmd.equals("rekey")) {
							session.rekey();
						}
						if (cmd.equals("compression")) {
							if (cmds.size() > 2) {
								txtResult.setText("compression level : " + level);
							}
							try {
								if (level == 0) {
									session.setConfig("compression.s2c", "none");
									session.setConfig("compression.c2s", "none");
								}
								else {
									session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
									session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
								}
							}
							catch (Exception e) {}
							session.rekey();
						}
					  	if(cmd.equals("version")){
						  	  txtResult.setText("SFTP protocol version "+ cSftp.version());
						  	}
						if(cmd.equals("help") || cmd.equals("?")){
						  	  txtResult.setText(help);
						}
					  	if(cmd.equals("ls") || cmd.equals("dir")){
					  		if (path == null || path.equals("")) {
					  			path = ".";
					  		}
						  	  try{
						  	    Vector<String> vv = cSftp.ls(path);
						  	    Vector<String> value = new Vector<String>();
						  	    String folder = "";
						  	    if(vv!=null){
						  	      for(int ii=0; ii<vv.size(); ii++){
						  	    	  	txtResult.setText("");
						                  Object obj=vv.elementAt(ii);
						                  if(obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
						                	  value.add(((com.jcraft.jsch.ChannelSftp.LsEntry)obj).getLongname() + "\n");
						                  	}
						                  }
						  	      }
						  	      for (int z=0;z<value.size(); z++) {
						  	      		folder = folder + value.get(z);
						  	      		}
						                  txtResult.setText(folder);

						  	    }
						  	  
						  	  catch(SftpException e){
						  	    Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
						  	  }
						  	}
					  	if (explode[0].equals("get") || explode[0].equals("get-resume") || explode[0].equals("get-append") ||
					  		explode[0].equals("put") || explode[0].equals("put-resume") || explode[0].equals("put-append")) {
					  		String type			= explode[0];
					  		String source		= explode[1];
				  			String destination	= explode[2];
					  		try {
						  	    SftpProgressMonitor monitor = new MyProgressMonitor();
					  			if (type.startsWith("get")) {
					  				int mode = ChannelSftp.OVERWRITE;
					  				if (type.equals("get-resume")) {
					  					mode = ChannelSftp.RESUME;
					  				}
					  				else if (type.equals("get-append")) {
					  					mode = ChannelSftp.APPEND;
					  				}
					  				cSftp.get(source, destination, monitor, mode);
					  			}
					  			else {
					  				int mode = ChannelSftp.OVERWRITE;
					  				if (type.equals("put-resume")) {
					  					mode = ChannelSftp.RESUME;
					  				}
					  				else if (type.equals("put-append")) {
					  					mode = ChannelSftp.APPEND;
					  				}
					  				cSftp.put(source, destination, monitor, mode);
					  			}
//					  			File outputFile = new File(wallpaperDirectory, source);
//						  		FileOutputStream fos = new FileOutputStream(outputFile);
				  				txtResult.setText("file : " + source + " have copied at " + destination);
					  		}
					  		catch (Exception e) {
								// TODO: handle exception
					  			Log.e("CheckConnectActivity", e.getMessage());
					  			Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
					  		}
					  	}
			        session.disconnect();
					}
	 			}
//			}
		}
	}
}
